package Flights;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.StringTokenizer;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="flights")
@SessionScoped
public class Flights {
	
	private HashMap<String, Flight> flights = new HashMap<String, Flight>();
	private ArrayList<Flight> allFlights = new ArrayList<Flight>();
	private Flight flight;
	
	public Flights(String path) {
		BufferedReader in = null;
		try {
			File file = new File(path);
			System.out.println(file.getCanonicalPath());
			in = new BufferedReader(new FileReader(file));
			readFlights(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			if ( in != null ) {
				try {
					in.close();
				}
				catch (Exception e) { }
			}
		}
	}

	private synchronized void readFlights(BufferedReader in) {
		String line, idLeta = "", vremePolaska = "", vremeDolaska = "", polaziAerodrom = "", odrediste="", brojPutnika="";
		StringTokenizer st;
		try {
			while ((line = in.readLine()) != null) {
				line = line.trim();
				if (line.equals("") || line.indexOf('#') == 0)
					continue;
				st = new StringTokenizer(line, ";");
				while (st.hasMoreTokens()) {
					idLeta = st.nextToken().trim();
					vremePolaska = st.nextToken().trim();
					vremeDolaska = st.nextToken().trim();
					polaziAerodrom = st.nextToken().trim();
					odrediste = st.nextToken().trim();
					brojPutnika = st.nextToken().trim();
				}
				Date date;
				Flight f = new Flight(idLeta, 
						date = new SimpleDateFormat("dd. MMMM yyyy, HH:mm").parse(vremePolaska),
						date = new SimpleDateFormat("dd. MMMM yyyy, HH:mm").parse(vremeDolaska),
						polaziAerodrom, odrediste, 
						Integer.parseInt(brojPutnika));
				flights.put(idLeta, f);
				allFlights.add(f);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public Collection<Flight> values() {
		return flights.values();
	}
	public Flight getFlight(String id) {
		return flights.get(id);
	}

	public ArrayList<Flight> getAllFlights() {
		return allFlights;
	}

	public void setAllFlights(ArrayList<Flight> allFlights) {
		this.allFlights = allFlights;
	}

	public Flight getFlight() {
		return flight;
	}

	public void setFlight(Flight flight) {
		this.flight = flight;
	}

	public HashMap<String, Flight> getFlights() {
		return flights;
	}
	
}
